package cz.cuni.mff.d3s.arcas.m2m;

import cz.cuni.mff.d3s.arcas.drdl.AbstractElement;
import cz.cuni.mff.d3s.arcas.intermediate.IntermediateDocument;

import java.util.Collection;
import java.util.List;

import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.mwe.core.WorkflowContext;
import org.eclipse.emf.mwe.core.issues.Issues;
import org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent2;
import org.eclipse.emf.mwe.core.monitor.ProgressMonitor;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.resource.XtextResource;

import com.google.common.collect.Iterables;
import com.google.inject.internal.Lists;

@SuppressWarnings("restriction")
public class DRDLToIntermediateWfComponent extends AbstractWorkflowComponent2 {

	private String modelSlot;
	private String outputSlot;

	public void setModelSlot(String modelSlot) {
		this.modelSlot = modelSlot;
	}

	public void setOutputSlot(String outputSlot) {
		this.outputSlot = outputSlot;
	}

	@Override
	protected void checkConfigurationInternal(Issues issues) {
		checkRequiredConfigProperty("modelSlot", modelSlot, issues);
		checkRequiredConfigProperty("outputSlot", outputSlot, issues);

	}
	@Override
	protected void invokeInternal(WorkflowContext ctx, ProgressMonitor m, Issues issues) {
		Collection<?> slotContent = (Collection<?>) ctx.get(modelSlot);
		if (slotContent==null) {
			issues.addError(String.format("Slot %s is empty", modelSlot));
			return;
		}
		List<AbstractElement> elements = Lists.newArrayList();
		for (Resource r : Iterables.filter(slotContent, XtextResource.class)) {
			for (AbstractElement e : EcoreUtil2.eAllOfType(r.getContents().get(0), AbstractElement.class)) {
				elements.add(e);
			}
		}
		if (elements.isEmpty()) {
			issues.addError("No AbstractElement instance found in model slot");
			return;
		}

		// execute the transformation
		IntermediateDocument transformed = new DRDLToIntermediate().transform(elements);
		ctx.set(outputSlot, transformed);
	}
}
